var objLogin = {
	login : function(event){
		event.stopPropagation();
		event.preventDefault();
		var username = $('#email').val().trim(), password = $('#password').val().trim();
		$("#errorInfo").html("");
		if (username === '' || password == '') {
			$("#errorInfo").html(" the user name and password cannot be empty ");
		} else {
			$.post('/signin/login', {
				"user_name" : username,
				"password" : password
			}, function(data) {
				if (data.result) {
					$("#errorInfo").html(" the user name or password error ");
				} else {
					objLogin.setloginbanner();
				}
			}, "json");
		}
	},
	setloginbanner : function(){
		$.post('/signin/isLogin', {
			"a" : "a"
		}, function(data) {
			if (data.result) {
				// @TODO 根据请求来源判断登陆成功之后跳转链接
				var currUrl = window.location.href, relUrl = document.referrer;
				if(relUrl != ""){
					if(relUrl.indexOf("index")>0 && currUrl.indexOf("index")>0 ){
						$($("#userloginbanner li").get(0)).html(
								'Welcome <a href="/account" class="username">'
										+ data.username + '</a>|<a href="/login/loginout" class="exit">sign out</a>');
						$($("#userloginbanner li").get(1)).html('<a href="/points">Points:'+data.points+'</a>');
					}else if(relUrl.indexOf("signin") > 0 && currUrl.indexOf("signin") > 0){
						window.location.href = "/index";
					}else if(relUrl.indexOf("signup") > 0 && currUrl.indexOf("index") >0 ){
						window.location.href = "/index";
					}else if(relUrl.indexOf("index") > 0 && currUrl.indexOf("signin") >0 ){
						window.location.href = "/index";
					}else if(relUrl.indexOf("index") == -1 && currUrl.indexOf("signin") >0 ){
						window.location.href = relUrl;
					}else{
						$($("#userloginbanner li").get(0)).html(
								'Welcome <a href="/account" class="username">'
										+ data.username + '</a>|<a href="/login/loginout" class="exit">sign out</a>');
						$($("#userloginbanner li").get(1)).html('<a href="/points">Points:'+data.points+'</a>');
					}
				}else{
					if(currUrl.indexOf("signup")>0){
						window.location.href = "/index";
					}else{
						$($("#userloginbanner li").get(0)).html(
								'Welcome <a href="/account" class="username">'
										+ data.username + '</a>|<a href="/login/loginout" class="exit">sign out</a>');
						$($("#userloginbanner li").get(1)).html('<a href="/points">Points:'+data.points+'</a>');
					}
				}
			}
		}, "json");
	}
};

$(function() {
	$('#login').click(objLogin.login);
	objLogin.setloginbanner();
	$('#regist').click(function(event){
		event.stopPropagation();
		event.preventDefault();
		window.location.href = "/signup";
	});
});

String.prototype.trim = function(){
	return this.replace(/(^\s*)|(\s*$)/g, "");
};